package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.OrdersDto;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entitry.*;
import com.itheima.reggie.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrdersService ordersService;
    @Autowired
    UserService userService;

    @Autowired
    AddressBookService addressBookService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    OrderDetailService orderDetailService;


    /**
     * 下单
     * @param orders
     * @param session
     * @return
     */
    @PostMapping("/submit")
    public R<String> submitOrder(@RequestBody Orders orders, HttpSession session){

        //设置订单的用户信息
        User user = (User) session.getAttribute("user");
        User userByid = userService.getById(user.getId());
        orders.setUserId(userByid.getId());
        orders.setUserName(userByid.getName());

        //设置订单收货人信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());

        //设置订单号
        long orderId = IdWorker.getId();
        orders.setNumber(String.valueOf(orderId));

        //设置订单状态
        orders.setStatus(2);

        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());

        //设置结账时间
        orders.setCheckoutTime(LocalDateTime.now());

        //获取购物车中的该用户的点餐数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,user.getId());
        List<ShoppingCart> list = shoppingCartService.list(lqw);

        //定义count用来接收总金额
        BigDecimal count = new BigDecimal(0);

        //获取订单详情数据,存入数据库
        for (ShoppingCart shoppingCart : list) {

            //获取数量和价格
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());

            //创建订单详情对象
            OrderDetail orderDetail = new OrderDetail();

            //将数据拷贝到订单详情
            BeanUtils.copyProperties(shoppingCart,orderDetail);

            //计算订单详情金额
            orderDetail.setAmount(amount.multiply(number));

            //计算总金额
            count = count.add(orderDetail.getAmount());

            //设置ID
            orderDetail.setId(IdWorker.getId());

            orderDetail.setOrderId(orderId);

            orderDetailService.save(orderDetail);
        }

        //设置订单总金额
        orders.setAmount(count);

        //添加订单信息
        ordersService.save(orders);

        //清空购物车
        shoppingCartService.remove(lqw);

        return R.success("清空购物车成功");
    }

    /**
     * 分页查询订单
     * @param page
     * @param pageSize
     * @param session
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> selectPage(int page,int pageSize,HttpSession session){

        //创建返回对象Dto
        Page<OrdersDto> resultPage = new Page<>();

        //获取当前用户
        User user = (User) session.getAttribute("user");

        //订单分页查询
        Page<Orders> pageCondition = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.eq(Orders::getUserId,user.getId());

        Page<Orders> orderPage = ordersService.page(pageCondition,lqw);

        //设置返回对象Dto的total
        resultPage.setTotal(orderPage.getTotal());

        List<Orders> records = orderPage.getRecords();

        //创建返回值对象Dto的集合
        List<OrdersDto> resultList = new ArrayList<>();

        //循环接收订单详情
        for (Orders record : records) {

            OrdersDto ordersDto = new OrdersDto();

            //拷贝订单数据
            BeanUtils.copyProperties(record,ordersDto);

            LambdaQueryWrapper<OrderDetail> lqw2 = new LambdaQueryWrapper<>();

            ordersDto.setOrderDetails(orderDetailService.list(lqw2));

            //加入集合
            resultList.add(ordersDto);
        }

        resultPage.setRecords(resultList);

        return R.success(resultPage);
    }

    @GetMapping("/page")
    public R<Page<Orders>> select(int page,int pageSize,Long number,String beginTime,String endTime){

        Page<Orders> ordersPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(number != null,Orders::getNumber,number);

        if (StringUtils.isNotEmpty(beginTime)){
            if (StringUtils.isNotEmpty(endTime)){
                lqw.between(Orders::getOrderTime,beginTime,endTime);
            }else {
                lqw.ge(Orders::getOrderTime,beginTime);
            }
        }else {
            if (StringUtils.isNotEmpty(endTime)){
                lqw.le(Orders::getOrderTime,endTime);
            }
        }
        Page<Orders> result = ordersService.page(ordersPage, lqw);

        return R.success(result);

    }
}
